import puppeteer from "puppeteer";
import { createEnumJosnFile } from '../service/createEnum'
import { IMethod } from "../../interface/type"
import { createApiFile } from '../service/createApi'
import { Server } from "../../store/server"
import { config } from "../../config"
import { MethodAction } from "./methodAction"
import { createListFile } from '../service/createList'
import { createEditFile } from '../service/createEdit'
import { createRouterFile } from '../service/createRouter'

export class IndexAction {
  private page: puppeteer.Page;
  private serverStore: Server;
  private browser: any;
  constructor(browser:any, page: puppeteer.Page) {
    this.page = page;
    this.serverStore = new Server()
    this.browser = browser
  }

  public async handleEnumHook(response: any) {
    if (response.url().indexOf("jsonEnum") > 0 && response.url().indexOf("jsonEnumString") === -1) {
      const json: JSON = await response.json();
      console.log("json >> ", json)
      createEnumJosnFile(json)
    }
  }

  public async getServerList(): Promise<any> {
    // 通过 page.evaluate 在浏览器里执行
    return await this.page.evaluate(() => {
      // 此处是在浏览器里执行，所以不能直接获取外部变量，如果直接使用titleList，这是获取不到的
      console.log("在浏览器里执行");
      // const tableList = document.querySelector('#service-methods')?.nextElementSibling?.children[1]
      const trList = document.querySelector("#service-methods")?.nextElementSibling?.children[1]?.children
      const list: IMethod[] = []
      if (trList && trList?.length > 0) {
        // for (let i = 0; i < trList.length; i++) {
        for (const it of trList) {
          console.log('内容：　', it?.querySelector('.title')?.textContent)
          // const it = trList[i]
          const aEl = it?.children[1]?.children[0]
          list.push({
            name: aEl?.textContent,
            link: aEl?.getAttribute("href"),
            description: it?.querySelector('.title')?.textContent
          })
        }
      }
      return list;
    });
  }

  public async startPageListen(): Promise<void> {
    console.log("开始页面监听");
    this.page.on("response", async (response: any) => {
      await this.handleEnumHook(response)
    })
  }

  public async loadOtherAction () {
    console.log('>>> 加载期页面')
    for (const item of config.pages ) {
      await new MethodAction(this.browser, this.serverStore, item.list).init((res) => {
        // request: req,
        // response: resp
        console.log('----res>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', res)
        createListFile(item, res)
      })
      console.log('创建路由')
      await createRouterFile(item)
      console.log('开始获取编辑参数')
      await new MethodAction(this.browser, this.serverStore, item.modify).init((result) => {
        console.log('----result:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', result)
        createEditFile(item, result.request)
      })
    }
  }

  public async init() {
    console.log("开始处理事务");
    // this.handleData();
    const list = await this.getServerList()
    for (const li of list) {
      this.serverStore.setMethod(li.name, li)
    }
    await createApiFile(list)
    console.log("获取到serve列表")
    console.log(list)
    await this.loadOtherAction()
  }


}